#include "myhttp.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

HTTPResponse getResponseString(char *sContentType, void *vptrContent, size_t iContentLength)
{
	HTTPResponse objHTTPResponse;
	objHTTPResponse.vptrResponse = malloc(iContentLength + 400);

	sprintf(objHTTPResponse.vptrResponse, "HTTP/1.1 200 OK\r\nServer: CS/241\r\nMIME-version: 1.0\r\nContent-type: %s\r\nContent-Length: %d\r\n\r\n", sContentType, iContentLength);
	objHTTPResponse.length = strlen((char*)objHTTPResponse.vptrResponse) + iContentLength;
	memcpy(objHTTPResponse.vptrResponse + strlen((char*)objHTTPResponse.vptrResponse), vptrContent, iContentLength);

	return objHTTPResponse;
}

HTTPResponse getFileNotFoundResponseString()
{
	HTTPResponse objHTTPResponse;
	char *sContent = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>HTTP/404 File Not Found</title></head><body><h1>Not Found</h1><div>Your requested file was not found on the server.</div></body></html>";

	objHTTPResponse.vptrResponse = malloc(strlen(sContent) + 400);
	((char*)objHTTPResponse.vptrResponse)[0] = '\0';
	sprintf(objHTTPResponse.vptrResponse, "HTTP/1.1 404 Not Found\r\nServer: CS/241\r\nConnection: close\r\nContent-Length: %d\r\n\r\n%s", strlen(sContent), sContent);
	objHTTPResponse.length = strlen((char*)objHTTPResponse.vptrResponse);

	return objHTTPResponse;
}

HTTPResponse getNotImplementedResponseString()
{
	HTTPResponse objHTTPResponse;
	char *sContent = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>HTTP/501 Not Implemented</title></head><body><h1>Not Implemented</h1><div>Your requested cannot be undersood by the server. Sorry.</div></body></html>";

	objHTTPResponse.vptrResponse = malloc(strlen(sContent) + 400);
	((char*)objHTTPResponse.vptrResponse)[0] = '\0';
	sprintf(objHTTPResponse.vptrResponse, "HTTP/1.1 501 Not Implemented\r\nServer: CS/241\r\nConnection: close\r\nContent-Length: %d\r\n\r\n%s", strlen(sContent), sContent);
	objHTTPResponse.length = strlen((char*)objHTTPResponse.vptrResponse);

	return objHTTPResponse;
}

char* getFileNameFromHTTPRequest(void *vptrRequest, size_t length)
{
	const char sGET[3] = { 'G', 'E', 'T' };
	char *sFileName = malloc(257);
	int i;

	if (length < 3)
		return NULL;
	
	if (memcmp(vptrRequest, sGET, 3) != 0)
		return NULL;

	for (i = 4; i < length && i < 4 + 256; i++)
	{
		char c = ((char*)vptrRequest)[i];
		if (c == ' ')
			break;
		
		sFileName[i - 4] = c;
	}
	sFileName[i - 4] = '\0';

	if (strstr(sFileName, "..") != NULL)
		return NULL;

	return sFileName;
}
